package com.citycloud.ccuap.tc.oauth2.service.impl;

import java.util.List;

import javax.annotation.Resource;

import com.citycloud.ccuap.commons.constants.GlobalPasswordAlgorithm;
import com.citycloud.ccuap.commons.web.config.WebGlobalNames;
import com.citycloud.ccuap.framework.util.AESUtil;
import com.citycloud.ccuap.framework.util.DESUtil;
import com.citycloud.ccuap.framework.util.MD5Util;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.citycloud.ccuap.commons.sys.entity.SysUser;
import com.citycloud.ccuap.tc.common.dto.DataCSecurityBasicUser;
import com.citycloud.ccuap.tc.oauth2.config.CustomerProperties;
import com.citycloud.ccuap.tc.oauth2.dto.DetailedUserInfo;
import com.citycloud.ccuap.tc.oauth2.mapper.UserMapper;
import com.citycloud.ccuap.tc.oauth2.repository.SysUserRepository;
import com.citycloud.ccuap.tc.oauth2.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	@Resource
	private SysUserRepository userRepository;

	@Resource
	private UserMapper userMapper;

	private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

	@Override
	public SysUser getByUsername(String username) {
		SysUser user = userRepository.findByUserNo(username);
		return user;
	}

	@Override
	public boolean isPlatformManager(Long userId) {
		int count = userMapper.isPlatformManager(userId, CustomerProperties.authorizationProjectId);
		return count > 0;
	}

	@Override
	public SysUser getByUserId(Long userId) {
		return userRepository.findById(userId).get();
	}

	@Override
	public DetailedUserInfo getDetailedUserInfo(DetailedUserInfo user) {
		return userMapper.getDetailedUserInfoById(user);
	}

	@Override
	public List<SysUser> findByUserNoAndStatus(String userNo, Integer status) {
		return userRepository.findByUserNoAndDataStatus(userNo, status);
	}

	@Override
	public void changPwd(DataCSecurityBasicUser basicUser, String oldPwd, String newPwd) {
		SysUser user = userRepository.findById(basicUser.getUserId()).get();
		if (WebGlobalNames.PASSWORD_ALGORITHM.equalsIgnoreCase(GlobalPasswordAlgorithm.MD5)) {
			if (MD5Util.md5(oldPwd).equals(user.getPassword())) {
				user.setPassword(MD5Util.md5(newPwd));
				try {
					user.setDesPassword(DESUtil.encrypt(newPwd));
				} catch (Exception e) {
					e.printStackTrace();
				}
				userRepository.update(user);
			} else {
				throw new RuntimeException("原密码错误！");
			}
		} else if (WebGlobalNames.PASSWORD_ALGORITHM.equalsIgnoreCase(GlobalPasswordAlgorithm.AES)) {
			if (AESUtil.Encrypt(oldPwd, WebGlobalNames.AES_KEY).equals(user.getPassword())) {
				user.setPassword(AESUtil.Encrypt(newPwd, WebGlobalNames.AES_KEY));
				try {
					user.setDesPassword(DESUtil.encrypt(newPwd));
				} catch (Exception e) {
					e.printStackTrace();
				}
				userRepository.update(user);
			} else {
				throw new RuntimeException("原密码错误！");
			}
		}


	}
}
